package com.lsk.gateway.Filter;

import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
public class MyGlobalFilter1 implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("进入全局过滤器");
        System.out.println("请求路径："+exchange.getRequest().getPath());
        System.out.println("请求方法："+exchange.getRequest().getMethod().name());
        System.out.println("请求参数："+exchange.getRequest().getQueryParams());
        long start = System.currentTimeMillis();
        
        ServerHttpResponse originalResponse = exchange.getResponse();
        
        // 创建装饰器来捕获响应体
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.map(dataBuffer -> {
                        // 读取响应体内容
                        byte[] content = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(content);
                        // 释放缓冲区
                        DataBufferUtils.release(dataBuffer);
                        
                        // 输出响应内容
                        String responseBody = new String(content, StandardCharsets.UTF_8);
                        System.out.println("响应体内容：" + responseBody);
                        
                        // 重新写入响应体到原始缓冲区工厂
                        return exchange.getResponse().bufferFactory().wrap(content);
                    }));
                }
                return super.writeWith(body);
            }
        };
        
        // 使用装饰后的响应对象
        return chain.filter(exchange.mutate().response(decoratedResponse).build())
                .doFinally((e) -> {
                    long end = System.currentTimeMillis();
                    System.out.println("请求耗时：" + (end - start) + "ms");
                    System.out.println("响应码：" + decoratedResponse.getStatusCode());
                    System.out.println("响应头：" + decoratedResponse.getHeaders());
                });
    }

    @Override
    public int getOrder() {
        return 0;
    }
}